<?php

namespace Viettrans\BackBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;

/**
 * Template controller.
 *
 * @Route("/bo/template")
 */
class TemplateController extends Controller {
    /**
     * @Route("/", name="bo_template_index")
     * @Template()
     */
    public function indexAction() {
		$viewsPath = $this->container->getParameter('views_path');
		
		$template = $this->getDirContent($viewsPath);

        return array(
			'template' => $template
		);
    }
	
	/**
	 * Template edit.
	 *
	 * @Route("/edit", name="bo_template_edit")
	 * @Template()
	 */
	public function editAction() {
		$request = $this->get('request');
		if ($request->getMethod() === "POST") {
			return array(
				'fileContent' => file_get_contents($request->get('filePath'))
			); 
		}
	}
	
	/**
	 * Template update.
	 *
	 * @Route("/update", name="template_update")
	 * @Template()
	 */
	public function updateAction() {
		$request = $this->get('request');
		if ($request->getMethod() === "POST") {
			$filePath = $request->get('filePath');
			$fileContent = $request->get('fileContent');
			
			# Clean the file content: trim replace Tab by 4 spaces
			$fileContent = trim(str_replace("\t", '    ', $fileContent));
			
			# If content is empty then KO
			if ($fileContent == '') return new Response('KO');
			
			$fileHandler = fopen($filePath, 'wt');
			if (!fwrite($fileHandler, $fileContent)) {
				fclose($fileHandler);
				return new Response('KO');
			}

			fclose($fileHandler);
			return new Response('OK');
		}
	}
	
	# Get the folder's content
	private function getDirContent($path) {
		# If folder does not exist then show the error
		if (!file_exists($path) || !is_dir($path)) throw new \Exception("The path $path does not exist.");
		
		$items = scandir($path);
		
		$content = array();
		
		foreach($items as $item) {
			if ($item == '.' || $item == '..') continue;

			if (is_dir($path.'/'.$item)) $content[] = array(
				'type'   => 'd',
				'name'   => $item,
				'path'   => $path.'/'.$item,
				'childs' => $this->getDirContent($path.'/'.$item),
			);
			else $content[] = array(
				'type' => 'f',
				'name' => $item,
				'path' => $path.'/'.$item,
			);
		};
		
		return $content;
	}
}
